from flask import current_app
from app.controller.validate.token_validate import TokenPostValidate
from app.extension.session.redis_session import r_session
from app.model.user_model import UserModel
import requests
from .shoutcut_import import *
bp = V1BluePoint('token', __name__, url_prefix='')


@bp.route('/token/ok', methods=['GET'])
def token_validate():
    """检验token是否合法"""
    token = request.headers.get('Token', None)
    if not token:
        return success_json({'ok': False})
    value = r_session.get(token)
    if not value:
        return success_json({'ok': False})
    return success_json({'ok': True})


@bp.route('token', methods=['POST'])
@validate_form(TokenPostValidate)
def create_token():
    """
    创建一个token 需要一个微信code
    1. 校验数据
    2. 获取小程序返回的code，根据code去请求微信接口
    3. 根据请求得到的session_key 和 openid 创建一个用户
    4. 创建一个随机key作为token，将uid数据存储到redis
    5. 返回给客户端token
    """
    # 1 获取openid
    code = request.json['code']
    try:
        r = requests.get(current_app.config['WECHAT_LOGIN_URL'].format(code))
    except Exception as e:
        print(e)
        return error_json(errcode=ResponseCode.INTERNAL_SERVER_ERROR, errmsg='请求微信接口失败')
    if r.json().get('errcode', None) is not None:
        return error_json(errcode=ResponseCode.REQUEST_ERROR, errmsg=r.json().get('errmsg', '请求微信接口失败'))
    # {'session_key': 'rKyCXxiG5CM7Od8cvmiORQ==', 'openid': 'opmqq5dhwzoF3k9T2fjp0e30Nrek'}
    openid = r.json().get('openid', None)
    if not openid:
        return error_json(errcode=ResponseCode.REQUEST_ERROR, errmsg='微信登录接口未返回openid')

    # 创建用户
    user = UserModel.query.filter_by(openid=openid).first()
    if not user:
        user = UserModel(openid)
        sqla_db.session.add(user)
        sqla_db.session.commit()
    uid = user.id
    if not uid:
        return error_json(errcode=ResponseCode.INTERNAL_SERVER_ERROR, errmsg='保存用户失败')

    session_data = {
        'session_key': r.json().get('session_key', ''),
        'openid': openid,
        'uid': uid,
        'scope': scope_map(user.type)
    }
    token = r_session.set(r_session.token, session_data)
    return success_json(data={'token': token})


@bp.route('token', methods=['delete'])
def delete_token():
    """
    删除一个token
    """
    pass
